<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"bamboowine.gitee.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="DFS&#x2F;DFS+记忆化搜索&#x2F;动态规划">
<meta property="og:type" content="article">
<meta property="og:title" content="分割等和子集 (01背包)">
<meta property="og:url" content="https://bamboowine.gitee.io/2021/07/28/leetcode/%E5%88%86%E5%89%B2%E7%AD%89%E5%92%8C%E5%AD%90%E9%9B%86%EF%BC%8801%E8%83%8C%E5%8C%85%EF%BC%89/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="DFS&#x2F;DFS+记忆化搜索&#x2F;动态规划">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210728095507652.png">
<meta property="og:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210728110508686.png">
<meta property="og:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210728112630620.png">
<meta property="og:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210728114606329.png">
<meta property="og:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210728135450448.png">
<meta property="og:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210728114704010.png">
<meta property="article:published_time" content="2021-07-28T07:04:28.000Z">
<meta property="article:modified_time" content="2021-07-29T15:24:14.698Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="leetcode周赛">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210728095507652.png">

<link rel="canonical" href="https://bamboowine.gitee.io/2021/07/28/leetcode/%E5%88%86%E5%89%B2%E7%AD%89%E5%92%8C%E5%AD%90%E9%9B%86%EF%BC%8801%E8%83%8C%E5%8C%85%EF%BC%89/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>分割等和子集 (01背包) | Hexo</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      
      <!-- 修改title -->
      <h1 class="site-title"> BambooWine's Notes </h1>
      <p class="site-subtitle" style="opacity: 1; top: 0px;">努力吧, 朋友~</p>
      <!-- <h1 class="site-title">Hexo</h1> -->

      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://bamboowine.gitee.io/2021/07/28/leetcode/%E5%88%86%E5%89%B2%E7%AD%89%E5%92%8C%E5%AD%90%E9%9B%86%EF%BC%8801%E8%83%8C%E5%8C%85%EF%BC%89/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="John Doe">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hexo">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          分割等和子集 (01背包)
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-07-28 15:04:28" itemprop="dateCreated datePublished" datetime="2021-07-28T15:04:28+08:00">2021-07-28</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-07-29 23:24:14" itemprop="dateModified" datetime="2021-07-29T23:24:14+08:00">2021-07-29</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">算法</span></a>
                </span>
            </span>

          
            <div class="post-description">DFS/DFS+记忆化搜索/动态规划</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="416-分割等和子集-01背包"><a href="#416-分割等和子集-01背包" class="headerlink" title="416. 分割等和子集 (01背包)"></a>416. 分割等和子集 (01背包)</h1><h2 id="1-题目"><a href="#1-题目" class="headerlink" title="1. 题目"></a>1. 题目</h2><p><a href="https://leetcode-cn.com/problems/partition-equal-subset-sum/" target="_blank" rel="noopener">题目链接</a></p>
<p><img src="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210728095507652.png" alt="image-20210728095507652"></p>
<h2 id="2-题目分析"><a href="#2-题目分析" class="headerlink" title="2. 题目分析"></a>2. 题目分析</h2><p>题目言简意赅，简言之就是从<code>nums</code>数组中挑选若干个元素，使其和等于<code>nums</code>所有元素和的一半；若存在这样的元素，返回true，否则返回false。</p>
<p>不难想到，<code>nuns</code>数组所有元素的和首先必须为偶数，故可以先做判断。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">bool</span> <span class="title">canPartition</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&amp; nums)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> sum = accumulate(nums.<span class="built_in">begin</span>(), nums.<span class="built_in">end</span>(), <span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span>(sum &amp; <span class="number">1</span>) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        	...</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>挑选若干元素，使其和等于<code>sum / 2</code>；后续的操作下面进行详细介绍：<strong>DFS</strong>、<strong>DFS+记忆化搜索</strong>、<strong>二维dp</strong>、<strong>一维dp</strong>。</p>
<h2 id="3-DFS"><a href="#3-DFS" class="headerlink" title="3. DFS"></a>3. DFS</h2><h3 id="3-1-DFS"><a href="#3-1-DFS" class="headerlink" title="3.1 DFS"></a>3.1 DFS</h3><p><strong>每一个元素仅有两个状态，选和不选</strong>。因此，所有的选取结果总共有<strong>2^n</strong>个；</p>
<p>在决策的时候，选取的过程类似一棵<strong>二叉树，左子树代表选取该元素，右子树代表不选该元素，而二叉树的深度代表当前元素所在的索引</strong>；以样例1<code>nums = [1,5,11,5]</code>进行说明，需要挑选若干元素使其等于<code>target = 11</code>，如图所示。</p>
<p><img src="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210728110508686.png" alt="image-20210728110508686"></p>
<p>从图中可以看出，节点为0说明存在若干元素和为11，而节点为负数则没必要再进行遍历。</p>
<p>但是在实际的DFS过程中，使用<strong>前序遍历</strong>，只要遇到节点为0的值就即可返回，所以并不一定需要遍历整棵树，所以最左端的0右边的所有子树不进行访问。</p>
<p>代码方面很简单，就是一个简单的前序遍历代码：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">bool</span> <span class="title">canPartition</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&amp; nums)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> sum = accumulate(nums.<span class="built_in">begin</span>(), nums.<span class="built_in">end</span>(), <span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span>(sum &amp; <span class="number">1</span>) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">return</span> helper(nums, sum / <span class="number">2</span>, <span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    * 进行前序遍历</span></span><br><span class="line"><span class="comment">    * @param nums: 原数组</span></span><br><span class="line"><span class="comment">    * @param target: 需要合成的目标值</span></span><br><span class="line"><span class="comment">    * @param s: 二叉树深度[元素所在索引]</span></span><br><span class="line"><span class="comment">    * @return bool: 节点是否存在0</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    <span class="function"><span class="keyword">bool</span> <span class="title">helper</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&amp; nums, <span class="keyword">int</span> target, <span class="keyword">int</span> s)</span></span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(target == <span class="number">0</span>) <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        <span class="comment">// target为负数 或 nums数组遍历完 返回false</span></span><br><span class="line">        <span class="keyword">if</span>(target &lt; <span class="number">0</span> || s == nums.<span class="built_in">size</span>()) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">return</span> helper(nums, target - nums[s], s + <span class="number">1</span>) || helper(nums, target, s + <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>很可惜，上述代码在第36个用例就会超时；其实这也是可以预见的，<code>nums</code>数组的长度为[0,200]；若数组过长，则树的节点超级多，遍历所有的节点超时是在所难免的，下一小节说明改进的方法。</p>
<p><img src="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210728112630620.png" alt="image-20210728112630620"></p>
<h3 id="3-2-DFS-记忆化搜索"><a href="#3-2-DFS-记忆化搜索" class="headerlink" title="3.2 DFS + 记忆化搜索"></a>3.2 DFS + 记忆化搜索</h3><p>在遍历过程中，难免会出现重复的节点，所谓<strong>重复的节点</strong>，是指<strong>二叉树同一深度中，值相等的节点</strong>，其需要由后续的元素进行合成，所以就出现了大量重复的计算。如上图的二叉树中最后一行，就出现了重复的节点（只不过原数组长度仅仅为4，这些重复的节点没有子树了）。</p>
<p>解决方法就是将访问过的节点用<strong>哈希表</strong>进行保存，<strong>包括其节点值的信息以及所在深度的信息</strong>；在遍历的过程中，如果出现重复的节点，则直接返回。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">bool</span> <span class="title">canPartition</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&amp; nums)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> sum = accumulate(nums.<span class="built_in">begin</span>(), nums.<span class="built_in">end</span>(), <span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span>(sum &amp; <span class="number">1</span>) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        <span class="built_in">unordered_map</span>&lt;<span class="built_in">string</span>, <span class="keyword">bool</span>&gt; mp;</span><br><span class="line">        <span class="keyword">return</span> helper(nums, mp, sum / <span class="number">2</span>, <span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    * 进行前序遍历</span></span><br><span class="line"><span class="comment">    * @param nums: 原数组</span></span><br><span class="line"><span class="comment">    * @param mp: 哈希表</span></span><br><span class="line"><span class="comment">    * @param target: 需要合成的目标值</span></span><br><span class="line"><span class="comment">    * @param s: 二叉树深度[元素所在索引]</span></span><br><span class="line"><span class="comment">    * @return bool: 节点是否存在0</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    <span class="function"><span class="keyword">bool</span> <span class="title">helper</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&amp; nums, <span class="built_in">unordered_map</span>&lt;<span class="built_in">string</span>, <span class="keyword">bool</span>&gt;&amp; mp, <span class="keyword">int</span> target, <span class="keyword">int</span> s)</span></span>&#123;</span><br><span class="line">        <span class="built_in">string</span> key = to_string(target) + <span class="string">'_'</span> + to_string(s);</span><br><span class="line">        <span class="keyword">if</span>(target == <span class="number">0</span>) <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        <span class="keyword">if</span>(target &lt; <span class="number">0</span> || s &gt;= nums.<span class="built_in">size</span>()) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">if</span>(mp.<span class="built_in">find</span>(key) != mp.<span class="built_in">end</span>()) <span class="keyword">return</span> mp[key];</span><br><span class="line">        <span class="keyword">bool</span> res = helper(nums, mp, target - nums[s], s + <span class="number">1</span>) || helper(nums, mp, target, s + <span class="number">1</span>);</span><br><span class="line">        mp[key] = res;</span><br><span class="line">        <span class="keyword">return</span> res;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>这样的代码就可以通过了。</p>
<p><img src="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210728114606329.png" alt="image-20210728114606329"></p>
<p>本代码中，哈希表的 key = target + ‘_’ + s 来保证其<strong>唯一性</strong>，但是哈希表用string作为key的类型，并不是完美的解决方案，所以再下一节对key的定义进行修改，使用int类型来存储。</p>
<h3 id="3-3-修改哈希表key的定义"><a href="#3-3-修改哈希表key的定义" class="headerlink" title="3.3 修改哈希表key的定义"></a>3.3 修改哈希表key的定义</h3><p>上一节中 <code>string key = to_string(target) + &#39;_&#39; + to_string(s)</code>，同时观察本题的数据量：</p>
<p><img src="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210728135450448.png" alt="image-20210728135450448"></p>
<p>可以得出，target ∈[0,  20000]，s∈[0, 200]，为了包含target和s的信息，同时保证key的唯一性，可以对其进行如下定义：<code>int key = target * 201 + s</code> 对代码优化。</p>
<p><img src="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210728114704010.png" alt="image-20210728114704010"></p>
<h2 id="4-动态规划"><a href="#4-动态规划" class="headerlink" title="4. 动态规划"></a>4. 动态规划</h2><p><strong>每一个元素仅有两个状态，选和不选</strong>；选若干元素使其和为<code>target = sum / 2</code>。</p>
<p>典型的<strong>01背包问题</strong>。</p>
<h3 id="4-1-二维dp"><a href="#4-1-二维dp" class="headerlink" title="4.1 二维dp"></a>4.1 二维dp</h3><h4 id="4-1-1-状态的定义"><a href="#4-1-1-状态的定义" class="headerlink" title="4.1.1 状态的定义"></a>4.1.1 状态的定义</h4><p>个人看来，状态的定义是dp中最难且最重要的一点，<strong>它的合适选取关系到状态转移方程的推到以及解题是否顺利</strong>。</p>
<p>dp[ i ] [ j ]：用前 i 个元素是否可以合成 j</p>
<p>i ∈ [0, n]</p>
<p>j ∈ [0, target]</p>
<h4 id="4-1-2-状态转移方程"><a href="#4-1-2-状态转移方程" class="headerlink" title="4.1.2 状态转移方程"></a>4.1.2 状态转移方程</h4><p>考虑dp[ i ] [ j ]的推导：</p>
<ul>
<li>若dp[ i - 1] [ j ]为 true，即可以用前 i - 1个元素合成 j，<strong>若不选第 i 个元素，则也可以用前 i 个元素合成 j</strong></li>
<li>若dp[i - 1] [j - nums[i]]为 true，即可以用前 i - 1个元素合成 j - nums[i]，<strong>若选第 i 个元素nums[i]，则可以用前 i 和 元素合成 j</strong></li>
</ul>
<p>综上所述：<strong><code>dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i]]</code></strong></p>
<h4 id="4-1-3-dp数组初始化"><a href="#4-1-3-dp数组初始化" class="headerlink" title="4.1.3 dp数组初始化"></a>4.1.3 dp数组初始化</h4><p>dp的递推需要对数组进行一定的初始化：</p>
<ul>
<li>首先dp数组全部元素可以设置为false</li>
<li>其次dp[i]] [0]，即数组第一列，可设置为true，含义为<strong>前 i 个元素合成0的方案只有1种，就是不选取任何元素</strong></li>
</ul>
<h4 id="4-1-4-完整代码"><a href="#4-1-4-完整代码" class="headerlink" title="4.1.4 完整代码"></a>4.1.4 完整代码</h4><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">bool</span> <span class="title">canPartition</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&amp; nums)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> sum = accumulate(nums.<span class="built_in">begin</span>(), nums.<span class="built_in">end</span>(), <span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span>(sum &amp; <span class="number">1</span>) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">int</span> n = nums.<span class="built_in">size</span>();</span><br><span class="line">        <span class="function"><span class="built_in">vector</span>&lt;<span class="built_in">vector</span>&lt;<span class="keyword">bool</span>&gt;&gt; <span class="title">dp</span><span class="params">(n + <span class="number">1</span>, <span class="built_in">vector</span>&lt;<span class="keyword">bool</span>&gt;(sum / <span class="number">2</span> + <span class="number">1</span>, <span class="literal">false</span>))</span></span>;</span><br><span class="line">        <span class="comment">// dp数组初始化</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt;= n; ++i) dp[i][<span class="number">0</span>] = <span class="literal">true</span>;</span><br><span class="line">        <span class="comment">// dp递推</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= n; ++i)&#123;</span><br><span class="line">            <span class="keyword">int</span> num = nums[i - <span class="number">1</span>];</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> j = <span class="number">1</span>; j &lt;= sum / <span class="number">2</span>; ++j)&#123;</span><br><span class="line">                dp[i][j] = dp[i - <span class="number">1</span>][j] || (j &gt;= num &amp;&amp; dp[i - <span class="number">1</span>][j - num]);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span>(dp[i][sum / <span class="number">2</span>]) <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h3 id="4-2-一维dp"><a href="#4-2-一维dp" class="headerlink" title="4.2 一维dp"></a>4.2 一维dp</h3><p>从上述代码可以看出，<strong>dp数组第 i 行的值只依赖于第 i - 1的值</strong>，因此可以进行<strong>空间优化</strong>——只需要用滚动数组保存上一行的值即可。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">bool</span> <span class="title">canPartition</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&amp; nums)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> sum = accumulate(nums.<span class="built_in">begin</span>(), nums.<span class="built_in">end</span>(), <span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span>(sum &amp; <span class="number">1</span>) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">int</span> n = nums.<span class="built_in">size</span>();</span><br><span class="line">        <span class="function"><span class="built_in">vector</span>&lt;<span class="keyword">bool</span>&gt; <span class="title">dp</span><span class="params">(sum / <span class="number">2</span> + <span class="number">1</span>, <span class="literal">false</span>)</span></span>;</span><br><span class="line">        dp[<span class="number">0</span>] = <span class="literal">true</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= n; ++i)&#123;</span><br><span class="line">            <span class="keyword">int</span> num = nums[i - <span class="number">1</span>];</span><br><span class="line">            <span class="built_in">vector</span>&lt;<span class="keyword">bool</span>&gt; tmp = dp;</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> j = <span class="number">1</span>; j &lt;= sum / <span class="number">2</span>; ++j)&#123;</span><br><span class="line">                dp[j] = tmp[j] || (j &gt;= num &amp;&amp; tmp[j - num]);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span>(dp[sum / <span class="number">2</span>]) <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>从这里的代码可以看到dp[j] 只依赖于 j 前面的值，故可以<strong>反向遍历</strong>以优化掉临时数组tmp。</p>
<p><strong>最终代码：</strong></p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">bool</span> <span class="title">canPartition</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&amp; nums)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> sum = accumulate(nums.<span class="built_in">begin</span>(), nums.<span class="built_in">end</span>(), <span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span>(sum &amp; <span class="number">1</span>) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">int</span> n = nums.<span class="built_in">size</span>();</span><br><span class="line">        <span class="function"><span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt; <span class="title">dp</span><span class="params">(sum / <span class="number">2</span> + <span class="number">1</span>, <span class="literal">false</span>)</span></span>;</span><br><span class="line">        dp[<span class="number">0</span>] = <span class="literal">true</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= n; ++i)&#123;</span><br><span class="line">            <span class="keyword">int</span> num = nums[i - <span class="number">1</span>];</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> j = sum / <span class="number">2</span>; j &gt;= num; --j)&#123;</span><br><span class="line">                dp[j] = dp[j] || (dp[j - num]);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span>(dp[sum / <span class="number">2</span>]) <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>


    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/leetcode%E5%91%A8%E8%B5%9B/" rel="tag"># leetcode周赛</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/07/07/leetcode/%E9%93%BE%E8%A1%A8%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95%E5%90%88%E9%9B%86/" rel="prev" title="链表排序算法总结">
      <i class="fa fa-chevron-left"></i> 链表排序算法总结
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/07/29/leetcode/%E7%9B%AE%E6%A0%87%E5%92%8C/" rel="next" title="目标和 (动态规划/01背包)">
      目标和 (动态规划/01背包) <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#416-分割等和子集-01背包"><span class="nav-number">1.</span> <span class="nav-text">416. 分割等和子集 (01背包)</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-题目"><span class="nav-number">1.1.</span> <span class="nav-text">1. 题目</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-题目分析"><span class="nav-number">1.2.</span> <span class="nav-text">2. 题目分析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-DFS"><span class="nav-number">1.3.</span> <span class="nav-text">3. DFS</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-DFS"><span class="nav-number">1.3.1.</span> <span class="nav-text">3.1 DFS</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-DFS-记忆化搜索"><span class="nav-number">1.3.2.</span> <span class="nav-text">3.2 DFS + 记忆化搜索</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-修改哈希表key的定义"><span class="nav-number">1.3.3.</span> <span class="nav-text">3.3 修改哈希表key的定义</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-动态规划"><span class="nav-number">1.4.</span> <span class="nav-text">4. 动态规划</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-二维dp"><span class="nav-number">1.4.1.</span> <span class="nav-text">4.1 二维dp</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-1-状态的定义"><span class="nav-number">1.4.1.1.</span> <span class="nav-text">4.1.1 状态的定义</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-2-状态转移方程"><span class="nav-number">1.4.1.2.</span> <span class="nav-text">4.1.2 状态转移方程</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-3-dp数组初始化"><span class="nav-number">1.4.1.3.</span> <span class="nav-text">4.1.3 dp数组初始化</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-4-完整代码"><span class="nav-number">1.4.1.4.</span> <span class="nav-text">4.1.4 完整代码</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-一维dp"><span class="nav-number">1.4.2.</span> <span class="nav-text">4.2 一维dp</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt=" BambooWine "
      src="/images/avatar.jpg">

  <!-- 修改作者 -->
  <p class="site-author-name" itemprop="name"> BambooWine </p>
  <!-- <p class="site-author-name" itemprop="name">John Doe</p> -->

  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">21</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
        <span class="site-state-item-count">2</span>
        <span class="site-state-item-name">分类</span>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  
  <span class="author" itemprop="copyrightHolder">BambooWine</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
